package com.module.frame.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment

abstract class AppBaseFragment : Fragment() {

    //    onAttach->onCreate->onCreateView->onViewCreated->onActivityCreated->onStart
    /**
     * 缓存Fragment view
     */
    lateinit var mRootView: View

    lateinit var mActivity: AppBaseActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is AppBaseActivity) {
            mActivity = activity as AppBaseActivity
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setContentView(inflater, container)
        val parent = mRootView.parent as? ViewGroup
        parent?.removeView(mRootView)
        return mRootView
    }

    open fun setContentView(layoutInflater: LayoutInflater, parent: ViewGroup?) {
        mRootView = layoutInflater.inflate(getLayoutId(), null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        mRootView.post { initData() }
    }

    /**
     * 获取布局 Id
     *
     * @return
     */
    @LayoutRes
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化View的代码写在这个方法中
     */
    protected abstract fun initView()

    /**
     * 初始化监听器的代码写在这个方法中
     */
    protected abstract fun initListener()

    /**
     * 初始数据的代码写在这个方法中，用于从服务器获取数据
     */
    protected abstract fun initData()


}